package com.toe.common.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class IpUtils {

    /**
     * 获取本地ip4
     * @return
     * @throws SocketException
     */
    public static String getLocalIp() throws SocketException {
        Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            Enumeration addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress ip = (InetAddress) addresses.nextElement();
                if (ip != null && ip.isSiteLocalAddress() && ip instanceof Inet4Address) {
                    String ipAddress = ip.getHostAddress();
                    if ("192.168.122.1".equals(ipAddress)) {
                        continue;
                    }
                    return ipAddress;
                }
            }
        }
        return "127.0.0.1";
    }

}
